# /Users/mac/hg/leecode

import os
import json
from pathlib import Path

def java_to_ipynb(java_dir, output_file):
    """
    将指定目录下的所有Java文件转换为一个IPython Notebook文件
    
    参数:
    java_dir: Java文件所在的目录路径
    output_file: 生成的IPython Notebook文件路径
    """
    # 初始化IPython Notebook的基本结构
    notebook = {
        "cells": [],
        "metadata": {
            "kernelspec": {
                "display_name": "Java",
                "language": "java",
                "name": "java"
            },
            "language_info": {
                "codemirror_mode": "java",
                "file_extension": ".java",
                "mimetype": "text/x-java-source",
                "name": "java"
            }
        },
        "nbformat": 4,
        "nbformat_minor": 5
    }
    
    # 遍历目录下的所有Java文件
    java_files = list(Path(java_dir).glob("**/*.java"))
    
    if not java_files:
        print(f"在目录 {java_dir} 中没有找到Java文件")
        return
    
    print(f"找到 {len(java_files)} 个Java文件，正在转换...")
    
    for java_file in java_files:    
        try:
            # 读取Java文件内容
            with open(java_file, 'r', encoding='utf-8') as f:
                java_code = f.read()
            
            # 创建代码单元格
            code_cell = {
                "cell_type": "code",
                "execution_count": None,
                "metadata": {},
                "outputs": [],
                "source": [java_code]
            }
            notebook["cells"].append(code_cell)
            
            print(f"已处理: {java_file}")
            
        except Exception as e:
            print(f"处理文件 {java_file} 时出错: {str(e)}")
            # 添加一个错误信息的markdown单元格
            error_cell = {
                "cell_type": "markdown",
                "metadata": {},
                "source": [f"⚠️ 读取文件时出错: {str(e)}"]
            }
            notebook["cells"].append(error_cell)
    
    # 将Notebook内容写入文件
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(notebook, f, ensure_ascii=False, indent=2)
    
    print(f"转换完成，结果已保存到 {output_file}")

if __name__ == "__main__":
    # 示例用法
    import sys
    
    if len(sys.argv) != 3:
        print("用法: python java_to_ipynb.py <java文件目录> <输出ipynb文件路径>")
        print("示例: python java_to_ipynb.py ./src ./java_files.ipynb")
        sys.exit(1)
    
    java_directory = sys.argv[1]
    output_ipynb = sys.argv[2]
    
    # 检查输入目录是否存在
    if not os.path.isdir(java_directory):
        print(f"错误: 目录 {java_directory} 不存在")
        sys.exit(1)
    
    java_to_ipynb(java_directory, output_ipynb)


